<template>
  <a-space direction="vertical">
    <a-card title="搜索">
      <a-form
        ref="searchRef"
        name="searchBar"
        :model="searchFormState"
        :labelCol="{ span: 5, offset: 1 }"
        @finish="handleSearch"
      >
        <a-row :gutter="24">
          <a-col :span="8">
            <a-form-item name="webServId" label="服务器ID">
              <a-input
                v-model:value="searchFormState[`webServId`]"
                placeholder=""
              ></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item name="servRemark" label="服务器名称">
              <a-input
                v-model:value="searchFormState[`servRemark`]"
                placeholder=""
              ></a-input>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24" style="text-align: right">
            <a-button type="primary" html-type="submit" :loading="searchLoading"
              >搜索</a-button
            >
            <a-button
              style="margin: 0 8px"
              @click="() => searchRef?.resetFields()"
              >重置</a-button
            >
          </a-col>
        </a-row>
      </a-form>
    </a-card>
    <a-card>
      <a-space>
        <a-button @click="showModal" type="primary"
          ><template #icon> <appstore-add-outlined /> </template>新增</a-button
        >
        <a-button @click="showEditModal"
          ><template #icon> <form-outlined /> </template>修改</a-button
        >
      </a-space>
    </a-card>
    <a-card title="查询结果">
      <a-table
        class="ant-table-striped"
        :rowClassName="
          (_record, index) => (index % 2 === 1 ? 'table-striped' : null)
        "
        :columns="columns"
        :data-source="data"
        rowKey="webServId"
        :loading="searchLoading"
        :rowSelection="rowSelection"
        @change="
          (pagination: any) => {
            handleSearch(pagination);
          }
        "
        :pagination="{
          position: [`bottomRight`],
          showSizeChanger: true,
          showQuickJumper: true,
          current: pageIndex,
          pageSize,
          total: total,
          showTotal: (total) => `总计 ${total} 条记录`,
        }"
      >
        <template #bodyCell="{ column, text }">
          <template v-if="column.dataIndex === 'name'">
            <a>{{ text }}</a>
          </template>
        </template>
      </a-table>
    </a-card>
    <a-modal
      ref="modalRef"
      v-model:visible="visible"
      @ok="handleOk"
      style="width: 1200px;top:0"
    >
      <template #title>
        <div ref="modalTitleRef" style="width: 100%; cursor: move">
          {{ currentAction }}服务器注册
        </div>
      </template>
      <!-- <template #modalRender="{ originVNode }">
        <div :style="transformStyle">
          <component :is="originVNode" />
        </div>
      </template> -->

      <a-form
        ref="formRef"
        :model="formState"
        :labelCol="{ span: 5, offset: 1 }"
        name="form_in_modal"
        
      >
      <a-row :gutter="24">
        <a-col :span="14" :offset="6">
            <a-form-item
              name="webServId"
              label="微前端服务器ID"
              :rules="[{ required: true, message: '请输入微前端服务器ID' }]"
            >
              <a-input v-model:value="formState.webServId" :disabled="currentAction == action.edit"/>
            </a-form-item>
            </a-col>
      </a-row>
      <a-row :gutter="24">
            <a-col :span="14" :offset="6">
            <a-form-item
              name="webServIp"
              label="IP地址及域名"
              :rules="[{ required: true, message: '请输入IP地址及域名' }]"
            >
              <a-input v-model:value="formState.webServIp" />
            </a-form-item>
            </a-col>
      </a-row>
      <a-row :gutter="24">
            <a-col :span="14" :offset="6">
            <a-form-item
              name="webServPort"
              label="端口"
              :rules="[{ required: true, message: '请输入端口' }]"
            >
              <a-input v-model:value="formState.webServPort" />
            </a-form-item>
          </a-col>
      </a-row>
      <a-row :gutter="24">
            <a-col :span="14" :offset="6">
            <a-form-item
              name="servRemark"
              label="微前端服务器名称"
              :rules="[{ required: true, message: '请输入微前端服务器名称' }]"
            >
              <a-input v-model:value="formState.servRemark" />
            </a-form-item>
          </a-col>
      </a-row>
      <a-row :gutter="24">
            <a-col :span="14" :offset="6">
            <a-form-item
              name="dataServers"
              label="后台数据服务器地址"
              :rules="[{ required: true, message: '请输入后台数据服务器地址' }]"
            >
              <a-input v-model:value="formState.dataServers" :disabled="currentAction == action.edit"/>
            </a-form-item>
           </a-col>
      </a-row>
      <a-row :gutter="24">
            <a-col :span="14" :offset="6">
            <a-form-item
              name="envType"
              label="环境类型"
              :rules="[{ required: true, message: '请输入环境类型' }]"
            >
              <a-input v-model:value="formState.envType" :disabled="currentAction == action.edit"/>
            </a-form-item>
          </a-col>
      </a-row>
          <a-row :gutter="24">
            <a-col :span="14" :offset="6">
            <a-form-item
              name="envLocal"
              label="地点"
              :rules="[{ required: true, message: '请输入地点' }]"
            >
              <a-input v-model:value="formState.envLocal" :disabled="currentAction == action.edit"/>
            </a-form-item>
          </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="14" :offset="6">
            <a-form-item
              name="rootNode"
              label="主应用匹配路径"
              :rules="[{ required: true, message: '请输入主应用匹配路径' }]"
            >
              <a-input v-model:value="formState.rootNode" />
            </a-form-item>
             </a-col>
         </a-row>
          <a-row :gutter="24">
            <a-col :span="14" :offset="6">
            <a-form-item
              name="webServPath"
              label="路由地址"
              :rules="[{ required: true, message: '请输入路由地址' }]"
            >
              <a-input v-model:value="formState.webServPath"/>
            </a-form-item>
             </a-col>
         </a-row>
         <!-- ismm新加的 -->
         <a-row :gutter="24">
            <a-col :span="14" :offset="6">
            <a-form-item
              name="aplResource"
              label="权限模型"
            >
              <a-select :allowClear="true" v-model:value="formState.aplResource" placeholder="">
                <a-select-option value="ismm">ismm</a-select-option>
                <a-select-option value="local">本地</a-select-option>
              </a-select>
            </a-form-item>
             </a-col>
         </a-row>
         <!-- 应用id -->
         <a-row :gutter="24">
            <a-col :span="14" :offset="6">
            <a-form-item
              name="aplId"
              label="应用id"
              :rules="[{ pattern: /^\d{6}$/, message: '应用id必须为6位数字' }]"
            >
              <a-input v-model:value="formState.aplId"/>
            </a-form-item>
             </a-col>
         </a-row>
         <!-- 应用名称 -->
         <a-row :gutter="24">
            <a-col :span="14" :offset="6">
            <a-form-item
              name="aplName"
              label="应用名称"
            >
              <a-input v-model:value="formState.aplName"/>
            </a-form-item>
             </a-col>
         </a-row>
      </a-form>
    </a-modal>
  </a-space>
</template>
<script lang="ts" setup>
// base library
import { LISTHEADER } from "./config";
import { serverQuery, serverAdd, serverEdit } from "@/api/supperManagement";
import { onMounted } from "@vue/runtime-core";
import {
  computed,
  createVNode,
  CSSProperties,
  reactive,
  ref,
  toRaw,
  unref,
  watch,
  watchEffect,
} from "vue";
import { FormInstance, message, Modal } from "ant-design-vue";
import { useDraggable } from "@vueuse/core";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";

const searchRef = ref<FormInstance>();
let searchLoading = ref(true);
const searchFormState: { [propName: string]: any } = reactive({});

const columns = LISTHEADER;
let pageIndex = ref(1);
let pageSize = ref(10);
let total = ref(0);
let data = ref([]);
const handleSearch = (values?: any) => {
  searchLoading.value = true;
  console.log("Received values of form: ", values);
  console.log("searchFormState: ", searchFormState);
  let parameter = { ...searchFormState };
  if (values?.current) {
    // 分页切换
    pageIndex.value = values?.current;
    pageSize.value = values?.pageSize;
  } else {
    // 搜索
    selectedRowKeys.value = [];
    selectedRows.value = [];
    pageIndex.value = 1;
  }
  const requestParameters = Object.assign({}, parameter, {
    pageIndex: pageIndex.value,
    pageSize: pageSize.value,
  });
  console.log("loadData request parameters:", requestParameters);

  serverQuery(requestParameters).then(
    (res: {
      code: number | string;
      msg: string;
      total: number;
      datas: any;
    }) => {
      searchLoading.value = false;
      const { code, msg, total: count, datas } = res;
      if (code === "777") {
        data.value = datas;
        total.value = count;
      } else {
        total.value = 0;
        data.value = [];
        pageIndex.value = 1;
        message.error(msg);
      }
    }
  );
};

const selectedRowKeys = ref<string[]>([]); // Check here to configure the default column
const selectedRows = ref<T[]>([]);
const onSelectChange = (changableRowKeys: string[], changableRows: T[]) => {
  console.log("selectedRowKeys changed: ", changableRowKeys);
  selectedRowKeys.value =
    changableRowKeys.length > 1 ? [changableRowKeys.pop()] : changableRowKeys;
  selectedRows.value =
    changableRows.length > 1 ? [changableRows.pop()] : changableRows;
};
const rowSelection = computed(() => {
  return {
    selectedRowKeys: unref(selectedRowKeys),
    onChange: onSelectChange,
    hideDefaultSelections: true,
  };
});

enum action {
  add = "新增",
  edit = "编辑",
}
const currentAction = ref(action.add);
const visible = ref<boolean>(false);
const modalTitleRef = ref<HTMLElement>(null);

const { x, y, isDragging } = useDraggable(modalTitleRef);
const startX = ref<number>(0);
const startY = ref<number>(0);
const startedDrag = ref(false);
const transformX = ref(0);
const transformY = ref(0);
const preTransformX = ref(0);
const preTransformY = ref(0);
const dragRect = ref({ left: 0, right: 0, top: 0, bottom: 0 });
watch([x, y], () => {
  if (!startedDrag.value) {
    startX.value = x.value;
    startY.value = y.value;
    const bodyRect = document.body.getBoundingClientRect();
    const titleRect = modalTitleRef.value.getBoundingClientRect();
    dragRect.value.right = bodyRect.width - titleRect.width;
    dragRect.value.bottom = bodyRect.height - titleRect.height;
    preTransformX.value = transformX.value;
    preTransformY.value = transformY.value;
  }
  startedDrag.value = true;
});
watch(isDragging, () => {
  if (!isDragging) {
    startedDrag.value = false;
  }
});
watchEffect(() => {
  if (startedDrag.value) {
    transformX.value =
      preTransformX.value +
      Math.min(Math.max(dragRect.value.left, x.value), dragRect.value.right) -
      startX.value;
    transformY.value =
      preTransformY.value +
      Math.min(Math.max(dragRect.value.top, y.value), dragRect.value.bottom) -
      startY.value;
  }
});
const transformStyle = computed<CSSProperties>(() => {
  return {
    transform: `translate(${transformX.value}px, ${transformY.value}px)`,
  };
});

interface FormValues {
  webServId: string;
  webServIp: string;
  webServPort: string;
  servRemark: string;
  dataServers: string;
  envType: string;
  envLocal: string;
  rootNode: string;
  webServPath:string;
  aplResource:string;
  aplId:string;
  aplName:string;
}
const formRef = ref<FormInstance>();
const formState = reactive<FormValues>({
  webServId: "",
  webServIp: "",
  webServPort: "",
  servRemark: "",
  dataServers: "",
  envType: "",
  envLocal: "",
  rootNode: "",
  webServPath: "",
  aplResource: "",
  aplId: "",
  aplName: "",
});
const showModal = () => {
  visible.value = true;
  formRef.value?.resetFields();
  currentAction.value = action.add;
  formState.webServId = "";
  formState.webServIp = "";
  formState.webServPort = "";
  formState.servRemark = "";
  formState.dataServers = "";
  formState.envType = "";
  formState.envLocal = "";
  formState.rootNode = "";
  formState.webServPath = "";
  formState.aplResource = "";
  formState.aplId = "";
  formState.aplName = "";
};
const showEditModal = () => {
  if (selectedRowKeys.value.length > 1)
    message.error("仅能选择一条记录进行操作");
  if (selectedRowKeys.value.length === 0)
    message.error("请选择一条记录进行操作");
  if (selectedRowKeys.value.length === 1) {
    currentAction.value = action.edit;
    visible.value = true;
    formRef.value?.resetFields();
    formState.webServId = selectedRows.value[0].webServId;
    formState.webServIp = selectedRows.value[0].webServIp;
    formState.webServPort = selectedRows.value[0].webServPort;
    formState.servRemark = selectedRows.value[0].servRemark;
    formState.dataServers = selectedRows.value[0].dataServers;
    formState.envType = selectedRows.value[0].envType;
    formState.envLocal = selectedRows.value[0].envLocal;
    formState.rootNode = selectedRows.value[0].rootNode;
    formState.webServPath = selectedRows.value[0].webServPath;
    formState.aplResource = selectedRows.value[0].aplResource;
    formState.aplId = selectedRows.value[0].aplId;
    formState.aplName = selectedRows.value[0].aplName;
  }
};
const handleOk = (e: MouseEvent) => {
  console.log(e);
  // visible.value = false;

  formRef.value
    .validateFields()
    .then((values) => {
      console.log("Received values of form: ", values);
      console.log("formState: ", toRaw(formState));
      visible.value = false;

      if (currentAction.value === action.add) {
        serverAdd(formState).then((res) => {
          const { code, msg } = res;
          if (code === "777") {
            Modal.success({
              title: msg,
            });
            formRef.value?.resetFields();
            console.log("reset formState: ", toRaw(formState));
          } else {
            Modal.error({
              title: msg,
            });
          }
          handleSearch();
        });
      }
      if (currentAction.value === action.edit) {
        serverEdit(formState).then((res) => {
          const { code, msg } = res;
          if (code === "777") {
            Modal.success({
              title: msg,
            });
            formRef.value?.resetFields();
            console.log("reset formState: ", toRaw(formState));
          } else {
            Modal.error({
              title: msg,
            });
          }
          handleSearch();
        });
      }
    })
    .catch((info) => {
      console.log("Validate Failed:", info);
    });
};
onMounted(() => {
  searchLoading.value = false;
  //   handleSearch();
});
</script>
<script lang="ts">
import {
  AppstoreAddOutlined,
  FormOutlined,
  DeleteOutlined,
  UsergroupAddOutlined,
  UserOutlined,
  ShareAltOutlined,
} from "@ant-design/icons-vue";

export default {
  name: "pageserverRigister",
  components: {
    AppstoreAddOutlined,
    FormOutlined,
    DeleteOutlined,
    UsergroupAddOutlined,
    UserOutlined,
    ShareAltOutlined,
  },
};
</script>

<style type="less" scoped>
/* .ant-form-item-label > label {
  width:150px!important;
  justify-content: end!important;
} */
.ant-table-striped :deep(.table-striped) td {
  background-color: #fafafa;
}

.ant-table-striped
  /deep/
  .ant-table-thead
  .ant-table-selection-column
  .ant-checkbox-wrapper {
  display: none;
}
</style>
